package com.xxx.service.impl;


import com.xxx.pojo.User;
import com.xxx.security.entity.SecurityUser;
import com.xxx.service.PermissionService;
import com.xxx.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 自定义userDetailsService - 认证用户详情
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    /***
     * 根据账号获取用户信息
     * (返回含有账号，密码，权限列表的User)
     * @param username:
     * @return:
     *
     * 在这个方法里，我们通过查询数据库，获取用户username、password和其对应的权限并设置到UserDetails对象里
     *
     */
    @Override
    public SecurityUser loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        User user = userService.selectByUsername(username);
        System.out.println("UserDetails:" + user);
        // 判断用户是否存在
        if (null == user) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        // 返回UserDetails实现类
        com.xxx.security.entity.User curUser = new com.xxx.security.entity.User();
        BeanUtils.copyProperties(user, curUser);
        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        System.out.println("UserDetails:" + authorities);

        SecurityUser securityUser = new SecurityUser(curUser);
        //赋值权限
        securityUser.setPermissionValueList(authorities);
        System.out.println(authorities);
        return securityUser;
    }

}
